package com.cty.Stack;

/*
* 用链表来模拟栈
* */
public class LinkedListStack {
    private Node head = new Node(0);//头节点
    private Node top = null;//栈顶指针

    //将数据压入栈中
    public void push(Node node) {
        //因为是链栈所以没有大小长度
        if (head.next == null) {
            //第一次压入数据
            head.next = node;
            top = node;
            return;
        }
        //将栈顶元素作为第一个有效节点(便于出栈和遍历)
        node.next = head.next;
        head.next = node;
        top = node;
    }

    //出栈
    public Node pop() {
        if (head.next == null) {
            throw new RuntimeException("栈空~~~~~");
        }
        //创建一个临时存储的变量
        Node node;
        //只有一个节点时
        if (head.next.next == null) {
            node = head.next;
            head.next =null;
            return node;
        }
        //正常情况
        node = head.next;
        head.next = head.next.next;
        return node;
    }

    //遍历链栈
    public void list() {
        //判空
        if (head.next == null) {
            System.out.println("链表为空~~~");
            return;
        }
        //创建一个辅助指针
        Node temp = head.next;
        while (temp != null) {
            System.out.printf("节点编号为%d\n",temp.no);
            temp = temp.next;
        }
    }
}
